#include<iostream>
#include<vector>
#include<map>
#include<algorithm>
using namespace std;

class Solution {
public:
    struct cmp
    {
        bool operator()(pair<string, int>& x, pair<string, int>& y)
        {
            return x.second > y.second || (x.second == y.second && x.first < y.first);
        }
    };

    vector<string> topKFrequent(vector<string>& words, int k)
    {
        map<string, int> cnt;
        for (auto e : words)
            cnt[e]++;
        vector<pair<string, int>> v(cnt.begin(), cnt.end());
        sort(v.begin(), v.end(), cmp());
        vector<string> ans;
        for (int i = 0; i < k; i++)
            ans.push_back(v[i].first);
        return ans;
    }
};